package com.bookocean.controller;

import com.bookocean.application.common.Result;
import com.bookocean.application.service.BookApplicationService;
import com.bookocean.domain.dto.BookCoverDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 文件上传控制器
 * 
 * @author BookOcean
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
public class FileController {

    private final BookApplicationService bookApplicationService;

    @Value("${file.upload.path:./uploads}")
    private String uploadPath;

    @Value("${file.upload.max-size:5242880}")
    private long maxFileSize;

    /**
     * 上传图片文件
     * 
     * @param file 图片文件
     * @return 文件访问URL
     */
    @PostMapping("/upload/image")
    public Result<String> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            // 参数校验
            if (file.isEmpty()) {
                return Result.error("文件不能为空");
            }
            // 检查文件大小
            if (file.getSize() > maxFileSize) {
                return Result.error("文件大小不能超过5MB");
            }
            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.error("只能上传图片文件");
            }
            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String fileName = UUID.randomUUID() + extension;
            // 按日期创建目录
            String datePath = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            // 创建目录
            Path uploadDir = Paths.get(uploadPath, "images", datePath);
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
            }
            // 保存文件
            Path filePath = uploadDir.resolve(fileName);
            Files.copy(file.getInputStream(), filePath);
            // 返回文件访问路径
            String fileUrl = "/api/file/images/" + datePath + "/" + fileName;
            log.info("文件上传成功: {}", fileUrl);
            return Result.success(fileUrl);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return Result.error("文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 获取封面素材列表
     * 
     * @param imageType 图片类型
     * @param userId 用户ID
     * @return 封面素材列表
     */
    @GetMapping("/covers")
    public Result<BookCoverDto[]> getCovers(@RequestParam("imageType") Integer imageType,
                                           @RequestParam("userId") String userId) {
        try {
            BookCoverDto[] covers = bookApplicationService.getCoversByType(imageType, userId);
            return Result.success(covers);
        } catch (Exception e) {
            log.error("获取封面素材失败", e);
            return Result.error("获取封面素材失败: " + e.getMessage());
        }
    }

    /**
     * 上传封面图片
     * 
     * @param file 封面图片文件
     * @param imageType 图片类型
     * @param userId 用户ID
     * @return 封面素材信息
     */
    @PostMapping("/upload/cover")
    public Result<BookCoverDto> uploadCover(@RequestParam("file") MultipartFile file,
                                           @RequestParam("imageType") Integer imageType,
                                           @RequestParam("userId") String userId) {
        try {
            // 参数校验
            if (file.isEmpty()) {
                return Result.error("文件不能为空");
            }
            if (file.getSize() > maxFileSize) {
                return Result.error("文件大小不能超过5MB");
            }
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.error("只能上传图片文件");
            }
            
            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String fileName = UUID.randomUUID() + extension;
            
            // 根据类型创建目录
            String categoryPath = getCategoryPath(imageType);
            Path uploadDir = Paths.get(uploadPath, "covers", categoryPath);
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
            }
            
            // 保存文件
            Path filePath = uploadDir.resolve(fileName);
            Files.copy(file.getInputStream(), filePath);
            
            // 返回文件访问路径
            String fileUrl = "/api/file/covers/" + categoryPath + "/" + fileName;
            
            // 保存到数据库
            BookCoverDto coverDto = new BookCoverDto();
            coverDto.setCoverUrl(fileUrl);
            coverDto.setImageType(imageType);
            coverDto.setUserId(userId);
            coverDto.setIsPublic(1); // 默认公开
            
            BookCoverDto savedCover = bookApplicationService.saveCover(coverDto);
            log.info("封面上传成功: {}", fileUrl);
            return Result.success(savedCover);
        } catch (Exception e) {
            log.error("封面上传失败", e);
            return Result.error("封面上传失败: " + e.getMessage());
        }
    }

    /**
     * 根据图片类型获取目录路径
     */
    private String getCategoryPath(Integer imageType) {
        switch (imageType) {
            case 1: return "history";
            case 2: return "literature";
            case 3: return "technology";
            case 4: return "art";
            case 5: return "philosophy";
            case 6: return "novel";
            case 7: return "biography";
            case 8: return "education";
            case 9: return "other";
            default: return "other";
        }
    }
}
